// export const BASE_URL = 'http://127.0.0.1:8085'
export const BASE_URL = 'https://campus-card.jxwazx.cn'
// export const BASE_URL = 'http://192.168.137.1:8085'

export function request(config = {}) {
  let { url, data = {}, loading = true, method = 'GET' } = config
  url = BASE_URL + url
  // 定义数组队列
  // 初始值需要是一个空数组，用来存储请求队列、存储请求标识
  var queue = []
  if (loading) {
    queue.length === 0 && setTimeout(() => {
      if (queue.length !== 0) {
        uni.showLoading({ title: '加载中', mask: true })
      }
    }, 500);;
    queue.push('request')
  }

  return new Promise((resolve, reject) => {
    uni.request({
      header: {
        Authorization: 'Bearer ' + uni.getStorageSync('token'),
      },
      url,
      data,
      method,
      success: (res) => {
        if (res.data.code === 0) {
          resolve(res.data)
        } else if (res.data.code === 400) {
          uni.showModal({
            title: '错误提示',
            content: res.data.message,
            showCancel: false,
          })
          reject(res.data)
        } else if (res.data.code === 401) {
          uni.redirectTo({
            url: '/pages/login/index'
          })

          // uni.showModal({
          //   title: '提示',
          //   content: '登录已过期',
          //   showCancel: false,
          // }).then(() => {
          //   uni.redirectTo({
          //     url: '/pages/login/index'
          //   })
          // })
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'none',
          })
          reject(res.data)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '服务器异常',
          icon: 'none',
        })
        reject(err)
      },
      complete: () => {
        if (loading) {
          queue.pop();
          setTimeout(() => {
            queue.length === 0 && uni.hideLoading();
          }, 0);
        }
      }
    })
  })
}
